package com.juzipi.demo.web.admin;


import com.juzipi.demo.pojo.User;
import com.juzipi.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 登陆页面
     * @return
     */
    @GetMapping
    public String loginPage() {

        return "admin/login";
    }

    /**
     * 登录
     * @param username
     * @param password
     * @param httpSession
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession httpSession,
                        RedirectAttributes redirectAttributes) {

        User user = userService.checkUser(username, password);
        if (!StringUtils.isEmpty(user)) {
            user.setPassword(null);
            httpSession.setAttribute("user",user);
            return "admin/index";
        }
        redirectAttributes.addFlashAttribute("message","用户名或密码错误");
        return "redirect:/admin";
    }


    /**
     * 退出
     * @param httpSession
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpSession httpSession) {
        httpSession.removeAttribute("user");
        return "redirect:/admin";
    }





}
